package com.ocm.commerceinteraction.ui;


import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.ocm.commerceinteraction.GlobalApplication;
import com.ocm.commerceinteraction.R;
import com.ocm.commerceinteraction.util.helper.LogHelper;
import com.ocm.commerceinteraction.util.view.ProgressWebView;
import com.ocm.commerceinteraction.util.view.percentsupport.PercentRelativeLayout;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;

import java.util.Date;


@EFragment(R.layout.fragment_advanture)
public class AdvantureFragment extends BaseFragment {
    @SuppressLint({ "JavascriptInterface", "SetJavaScriptEnabled" })
    private static final String TAG = "AdvantureFragment";
    //   @ViewById(R.id.back_btn)
//    ImageButton backBtn;
//
    @ViewById(R.id.toptitle_title)
    TextView topTitle;
    //    @ViewById(R.id.recyclerview)
//    RecyclerView recyclerView;
//
    AdvantureFragment homeFragment;
    @ViewById(R.id.back_btn)
    PercentRelativeLayout backBtn;

    @ViewById(R.id.ad_webview)
    ProgressWebView adWebview;

    @AfterViews
    @Override
    void initView() {
        homeFragment = this;
        topTitle.setText("格子广告");
        //backBtn.setVisibility(View.GONE);
        loadData();
    }
    @Click(R.id.back_btn)
    void  backBtnClick(){
        adWebview.goBack();
    }

    private ValueCallback<Uri> mUploadMessage;
    ValueCallback<Uri[]> mUploadCallbackAboveL;
    private final static int FILECHOOSER_RESULTCODE = 1;
    //加载数据
    private void loadData() {

        adWebview.getSettings().setJavaScriptEnabled(true);
        String url= "http://bchat.ocmcom.com/HGrid/grid?time=" + new Date().getTime();
        //       String url = "http://www.jq22.com/yanshi1845";
        WebSettings settings = adWebview.getSettings();
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setJavaScriptEnabled(true);
        settings.setSupportZoom(true);
        adWebview.setVerticalScrollBarEnabled(true);
        adWebview.setHorizontalScrollBarEnabled(true);
        adWebview.setWebChromeClient(new WebChromeClient() {
            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
            }

            // For Android 3.0+
            public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                startActivityForResult(
                        Intent.createChooser(i, "File Browser"),
                        FILECHOOSER_RESULTCODE);
            }

            //For Android 4.1
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
            }

            // For Android 5.0+
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                mUploadCallbackAboveL = filePathCallback;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                startActivityForResult(
                        Intent.createChooser(i, "File Browser"),
                        FILECHOOSER_RESULTCODE);
                return true;
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                if(title!=null){
                    topTitle.setText(title);
//                    if(title.equals("个人信息")){
//                        submint.setVisibility(View.VISIBLE);
//                    }else{
//                        submint.setVisibility(View.GONE);
//                    }
                }

            }
        });
//        adWebview.setOnLongClickListener(new View.OnLongClickListener() {
//            @Override
//            public boolean onLongClick(View view) {
//                return true;
//            }
//        });
//        adWebview.addJavascriptInterface(this, "ocm");
        //newsWebview.setBarHeight(3);
        adWebview.setWebViewClient(new WebViewClient() {

            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
//        getActivity().setContentView(adWebview);
        syncCookie(getActivity(), url);
        adWebview.loadUrl(url);
    }
    private void syncCookie(Context context, String url) {
        try {
           // Log.d("Nat: webView.syncCookie.url", url);
            CookieSyncManager.createInstance(context);
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptCookie(true);
            cookieManager.removeSessionCookie();// 移除
            cookieManager.removeAllCookie();
            LogHelper.i(" GlobalApplication.localCookie:" + GlobalApplication.localCookie.getCookies());

            StringBuilder sbCookie = new StringBuilder();
            sbCookie.append(String.format("PHPSESSID=%s", GlobalApplication.localCookie.getCookies().get(0).getValue()));
            sbCookie.append(String.format(";domain=%s", "bchat.ocmcom.com"));
            sbCookie.append(String.format(";path=%s", "/"));

            String cookieValue = sbCookie.toString();
            cookieManager.setCookie(url, cookieValue);
            CookieSyncManager.getInstance().sync();

            String newCookie = cookieManager.getCookie(url);
            if (newCookie != null) {
               // Log.d("Nat: webView.syncCookie.newCookie", newCookie);
            }
        } catch (Exception e) {
           // Log.e("Nat: webView.syncCookie failed", e.toString());
        }
    }
    // 一下2个方法解决  onShowFileChooser只加载一次的问题
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e(TAG, "onActivityResult: ");
        if(requestCode==FILECHOOSER_RESULTCODE)
        {
            if (null == mUploadMessage && null == mUploadCallbackAboveL) return;
            Uri result = data == null || resultCode != Activity.RESULT_OK ? null : data.getData();
            if (mUploadCallbackAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            }
            else  if (mUploadMessage != null) {
                mUploadMessage.onReceiveValue(result);
                mUploadMessage = null;
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
        Log.e(TAG, "onActivityResultAboveL: ");
        if (requestCode != FILECHOOSER_RESULTCODE
                || mUploadCallbackAboveL == null) {
            return;
        }

        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (data == null) {
            } else {
                String dataString = data.getDataString();
                ClipData clipData = data.getClipData();

                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }

                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }
        mUploadCallbackAboveL.onReceiveValue(results);
        mUploadCallbackAboveL = null;
        return;
    }
    @Override
    void Click(View view) {

    }


}
